package com.shop.shoporder.common;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.http.Response;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

//@Controller
public class UploadController {

    private String accessKey = "Wxb_fTMfyHgH_bVK22iwWbZuRjGuygRQTDK3Cp2r";
    private String secretKey = "PpkRQboOtBnTA0o27ch0NpM93peHmrp3w7W108yb";
    private String bucket = "resources";
    private String domainName = "http://resources.ycsqd.com/";

    @ResponseBody
    @RequestMapping(value = "/UploadFile")
    public JSONObject UploadFile(HttpServletRequest request) {
        return Upload(request,50*1024*1024);
    }

    @ResponseBody
    @RequestMapping(value = "/UploadFile10")
    public JSONObject UploadFile10(HttpServletRequest request) {
        return Upload(request,10*1024);
    }

    @ResponseBody
    @RequestMapping(value = "/UploadFile30")
    public JSONObject UploadFile0(HttpServletRequest request) {
        return Upload(request,30*1024);
    }

    @ResponseBody
    @RequestMapping(value = "/UploadFile50")
    public JSONObject UploadFile50(HttpServletRequest request) {
        return Upload(request,50*1024);
    }

    @ResponseBody
    @RequestMapping(value = "/UploadFile100")
    public JSONObject UploadFile100(HttpServletRequest request) {
        return Upload(request,100*1024);
    }

    @ResponseBody
    @RequestMapping(value = "/UploadFile200")
    public JSONObject UploadFile200(HttpServletRequest request) {
        return Upload(request,200*1024);
    }

    @ResponseBody
    @RequestMapping(value = "/UploadFile300")
    public JSONObject UploadFile00(HttpServletRequest request) {
        return Upload(request,300*1024);
    }

    @ResponseBody
    @RequestMapping(value = "/Upload")
    public JSONObject Upload(HttpServletRequest request,long maxSize) {

        System.out.println(maxSize);

        JSONObject resObj = new JSONObject();
        resObj.put("msg", "error");
        resObj.put("code", 1);
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
            String logoPathFile = dateformat.format(new Date());
            /** 页面控件的文件流* */
            MultipartFile multipartFile = multipartRequest.getFile("file");
            /** 获取文件的后缀* */
            String suffix = multipartFile.getOriginalFilename().substring(
                    multipartFile.getOriginalFilename().lastIndexOf("."));

            System.out.println("|"+suffix.toLowerCase()+"|");

            //判断后缀
            if(!("|.jpg|.png|".contains("|"+suffix.toLowerCase()+"|")))
            {
                resObj.put("msg", "文件类型错误");
            }
            else {

                //判断文件大小
                long size = multipartFile.getSize();
                if(size>maxSize)
                {
                    resObj.put("msg", "文件大小超过"+maxSize/1024+"KB");
                }
                else {
                    System.out.println("文件大小" + size);

                    /** 使用日期生成文件名称* */
                    String fileName = logoPathFile + Md5.getRandomNumCode(4) + suffix;// 构建文件名称

                    System.out.println(fileName);

                    //构造一个带指定Zone对象的配置类
                    Configuration cfg = new Configuration(Zone.zone2());

                    //...其他参数参考类注释
                    UploadManager uploadManager = new UploadManager(cfg);
                    //...生成上传凭证，然后准备上传

                    //获取流
                    byte[] uploadBytes = multipartFile.getBytes();
                    //默认不指定key的情况下，以文件内容的hash值作为文件名
                    String key = fileName;
                    Auth auth = Auth.create(accessKey, secretKey);
                    String upToken = auth.uploadToken(bucket);
                    try {
                        Response response = uploadManager.put(uploadBytes, key, upToken);
                        //解析上传成功的结果
                        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                        System.out.println(putRet.key);
                        System.out.println(putRet.hash);
                        resObj.put("msg", "ok");
                        resObj.put("code", 0);
                        resObj.put("fileName", domainName + fileName);
                    } catch (QiniuException ex) {
                        Response r = ex.response;
                        System.err.println(r.toString());
                        try {
                            System.err.println(r.bodyString());
                        } catch (QiniuException ex2) {
                            //ignore
                        }
                    }
                }
            }

        } catch (Exception ex) {
            System.err.println("XXX" + ex.getMessage());
        }
        return resObj;
    }

}
